<?

require_once("mysql.php");

$A = trim(strtolower($_GET['address'])); 
$L = trim(strtolower($_GET['location']));
$S = trim(strtolower($_GET['search']));


$q = "SELECT * FROM placesearch WHERE location='%s' AND search='%s'";
$q = sprintf($q, ESC($L), ESC($S));
$r = MYSQL_Q($q);
$c = mysql_num_rows($r);
 
/*
 * slice off the 'html_attributions' field because that causes some issues in encoding
 */
function filter_google_places_search_result($p) {

    return array_slice($p, 1,1);

}

if ($c == 1) {

    // if we have found the search query (location+seller) in our saved cache then return that

    $row = mysql_fetch_assoc($r);

    echo ($row['results']);

    MYSQL_Q("UPDATE placesearch SET count=".($row['count']+1)." WHERE location='".ESC($L)."' AND search='".ESC($S)."'");



} else if ($c == 0) {
    // otherwise do a google search


    $APPKEY = "AIzaSyBQZ7w1bdCtYlJ1XYHCw6CWhuwUybKs6fs";
    $SEARCH = "https://maps.googleapis.com/maps/api/place/search/json?location=".$L."&radius=20000&keyword=".urlencode($S)."&sensor=false&key=".$APPKEY;
     

    $raw = file_get_contents($SEARCH);

    $php = json_decode($raw, true);

    //TODO:  make sure $php data structure is sane

    $php = filter_google_places_search_result($php);

    $json = json_encode($php);
    
    echo $json;

    $q = "INSERT INTO placesearch (location, address, search, time, results) VALUES ('%s', '%s', '%s', UNIX_TIMESTAMP(NOW()), '%s')";
    $q = sprintf($q, ESC($L), ESC($A), ESC($S), mysql_real_escape_string($json));
    MYSQL_Q($q);
}


 
?>
